package com.fast.server.controller;

import com.fast.server.config.captcha.CreateImageConfig;
import com.fast.server.entity.constants.Constants;
import com.fast.server.entity.responseVO.RespBean;
import com.fast.server.exception.BusinessException;
import com.fast.server.service.ISysVerificationCodeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * <p>
 * 图形验证码API
 * </p>
 *
 * @author ziyuancheng
 * @since 2024-05-02
 */
@Api(tags = "验证码API")
@RestController
@RequestMapping(value = "/captcha")
public class CaptchaController {

    @Autowired
    private ISysVerificationCodeService verificationCodeService;

    @ApiOperation(value = "登陆界面验证码", produces = "image/jpg")
    @RequestMapping(value = "/checkCode")
    public void checkCode(HttpServletResponse response, HttpSession session, Integer type) throws IOException {
        CreateImageConfig vCode = new CreateImageConfig(130, 38, 1, 10);
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        String code = vCode.getCode();
        if (type == null || type == 0) {
            session.setAttribute(Constants.CHECK_CODE_KEY, code);
        } else {
            session.setAttribute(Constants.CHECK_CODE_KEY_EMAIL, code);
        }
        vCode.write(response.getOutputStream());
    }


    @ApiOperation(value = "发送邮箱验证码", produces = "image/jpg")
    @RequestMapping("/sendEmailCode")
    public RespBean sendEmailCode(HttpSession session, String email, String checkCode, Integer type) {
        try {
            if (!checkCode.equalsIgnoreCase((String) session.getAttribute(Constants.CHECK_CODE_KEY_EMAIL))) {
                throw new BusinessException("图片验证码不正确");
            }
            verificationCodeService.sendEmailCode(email, type);
            return RespBean.success();
        } finally {
            session.removeAttribute(Constants.CHECK_CODE_KEY_EMAIL);
        }
    }





}
